<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-02-05 22:25:37
 * Desc:
 */

namespace app\admin\controller\user;

use app\admin\controller\adminAuthController;
use app\base\model\user\{User, UserWx, UserFriend, UserAccount, UserStatisticsInfo};
use app\core\exception\{ErrorCode, BusinessException};
use app\core\util\PreVentRepeatSubmitUtil;
use app\core\cache\RedisKeys;
use app\core\util\TokenUtil;
use think\Request;
use think\Db;
use app\core\log\Log4dd;

class UserController extends adminAuthController
{

    public function getUserList()
    {
        $size = input('page_size/d', 20);
        $page = input('page/d', 1);
        $where = [];

        $account_type = input('account_type/d', 0);

        if ($account_type) {
            $where['user.account_type'] = $account_type;
        }

        $start_time = input('start_time/s', '');
        $end_time = input('end_time/s', '');
        if ($start_time && $end_time) {
            $where['user.register_time'] = ['BETWEEN', [$start_time, $end_time]];;
        } elseif ($start_time) {
            $where['user.register_time'] = ['>=', $start_time];
        } elseif ($end_time) {
            $where['user.register_time'] = ['<=', $end_time];
        }


        $is_pay_user = input('is_pay_user/d', 0);

        if ($is_pay_user) {
            $where['user_s.pay_num'] = ['>', 0];
        }

        $data = User::adminGetUserList($where, $page, $size);

        return $this->successReturn($data);

    }

    public function getRobotList()
    {
        $data = [];
        $items = User::adminGetRobotList();

        if ($items) {
            foreach ($items as $item) {
                $data[] = [
                    'label' => $item['nick_name'],
                    'value' => $item['user_id'],
                ];
            }
        }

        return $this->successReturn(['data' => $data]);

    }

    public function getUserInfo()
    {

        $user_id = input('user_id/d', 0);

        if (empty($user_id)) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, 'user_id不能为空');
        }

        $user_info = User::getUserInfoById($user_id);

        $wish_coin_num = UserAccount::getWishCoinNumByUserId($user_id);

        $statistics_info = UserStatisticsInfo::find($user_id);


        $data = [
            'user_info' => $user_info,
            'statistics_info' => $statistics_info,
            'wish_coin_num' => $wish_coin_num
        ];

        return $this->successReturn(['data' => $data]);
    }

    public function updateUserInfo()
    {
        $user_id = input('user_id/d', 0);

        if (empty($user_id)) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, 'user_id不能为空');
        }

        $model = User::get($user_id);

        if ($model == null) {
            return $this->errorReturn(ErrorCode::DATA_NOT_FOUND);
        }

        $account_type = input('account_type/d');
        $account_status = input('account_status/d');
        $nickname = input('nickname/s');
        $avatar_url = input('avatar_url/s');

        $data = [];
        $account_type && $data['account_type'] = $account_type;
        $account_status && $data['account_status'] = $account_status;
        $nickname && $data['nick_name'] = $nickname;
        $avatar_url && $data['small_avatar_url'] = $avatar_url;
        $avatar_url && $data['big_avatar_url'] = $avatar_url;

        if ($data) {
            User::setUserInfoById($user_id, $data);
        }

        return $this->successReturn();
    }

    public function addRobot()
    {
        Log4dd::info('后台新增机器人', [$this->adminId, Request::instance()->param(false)]);
        $nick_name = input('nick_name/s', '');
        $gender = input('gender/d', 0);
        $avatar_url = input('avatar_url/s', '');

        if (empty($nick_name)) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '昵称不能为空');
        }

        if (empty($gender)) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '性别不能为空');
        }

        if (empty($avatar_url)) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '头像不能为空');
        }

        $user = [
            'nick_name' => $nick_name,
            'gender' => $gender,
            'small_avatar_url' => $avatar_url,
            'big_avatar_url' => $avatar_url,
            'account_type' => User::ACCOUNT_TYPE_ROBOT,
            'refer_code' => User::genReferCode(),
            'register_time' => date('Y-m-d H:i:s'),
            'register_ip' => Request::instance()->ip()
        ];

        $ret = User::create($user);

        return $ret ? $this->successReturn() : $this->errorReturn();

    }

    public function manualOperatingAccount()
    {
        $user_id = input('user_id/d', 0);

        if (empty($user_id)) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, 'user_id不能为空');
        }

        $user_info = User::getUserInfoById($user_id);

        if (empty($user_info)) {
            return $this->errorReturn(ErrorCode::DATA_NOT_FOUND, '用户不存在');
        }

        $wish_value = input('wish_value/f', 0);

        if (empty($wish_value)) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '要操作的心愿值数量不能为空');
        }

        if ($wish_value > 10000) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '金额过大');
        }

        try {
            //防重复提交
            PreVentRepeatSubmitUtil::check(RedisKeys::getAdminManualOperatingAccount($user_id));
            $res = UserAccount::operationUserAccount($user_id, $user_id, UserAccount::WISH_COIN,
                $wish_value, 'admin_manual', '系统管理员赠送');

            Log4dd::info('后台手动赠送心愿值', ['admin_id' => $this->adminId, 'admin_info' => $this->adminInfo, 'params' => Request::instance()->param(), 'res' => $res]);

            if ($res && isset($res['err_num']) && $res['err_num'] == 0) {
                return $this->successReturn();
            } else {
                return $this->errorReturn();
            }

        } catch (BusinessException $e) {
            return $this->errorReturn($e->getCode(), $e->getMessage());
        }

    }

    public function unBIndUser()
    {
        $user_id = input('user_id/d', 0);

        if (empty($user_id)) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, 'user_id不能为空');
        }

        $wx_id = UserWx::where('user_id', $user_id)->where('app_id', 'wx5a158ad716b5e959')->where('open_id_type', UserWx::MINI_PROGRAM_OPEN_ID_TYPE)->value('wx_id');

        if (empty($wx_id)) {
            return $this->errorReturn(ErrorCode::DATA_NOT_FOUND, '绑定信息不存在');
        }

        Db::startTrans();

        try {
            $res = User::where('user_id', $user_id)->update(['account_status' => User::ACCOUNT_STATUS_LOGOUT]);
            $ret = UserWx::where('wx_id', $wx_id)->update(['user_id' => 0, 'is_follow' => 0, 'update_time' => date('Y-m-d H:i:s')]);
            Log4dd::info('手动解绑用户', ['admin_id' => $this->adminId, 'admin_info' => $this->adminInfo, 'params' => Request::instance()->param(), 'wx_id' => $wx_id, 'ret' => $ret]);
            if ($res && $ret) {
                TokenUtil::delApiLoginTokenCopy($user_id);
                Db::commit();
                return $this->successReturn();
            }

            Db::rollback();
            return $this->errorReturn();
        } catch (BusinessException $e) {
            Db::rollback();
            Log4dd::error("手动解绑用户失败:{$e->getMessage()}", func_get_args(), $e);
            throw new BusinessException(ErrorCode::COMMON_ERROR, '解绑失败');
        }


    }

    public function bindFriend()
    {
        $user_id = input('user_id/d', 0);

        $friend_str = input('friend_str/s', '');

        if (strpos($friend_str, '，')) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '不能使用中文逗号');
        }

        $friend_ids = array_unique(array_filter(explode(',', $friend_str)));

        if (empty($friend_ids)) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, 'friend_id不能为空');
        }

        $not_exists_user_ids = '';
        if ($user_id) {
            $refer_code = User::getUserFieldById($user_id, 'refer_code');
            if (empty($refer_code)) {
                return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '用户不存在');
            }

            foreach ($friend_ids as $friend_id) {
                $refer_code = User::getUserFieldById($friend_id, 'refer_code');
                if (empty($refer_code)) {
                    $not_exists_user_ids .= $friend_id . ',';
                    continue;
                }

                UserFriend::bindFriendByFriendUserId($user_id, $friend_id, 'admin_bind');
                UserFriend::bindFriendByFriendUserId($friend_id, $user_id, 'admin_bind');
            }
        } else {
            foreach ($friend_ids as $key => $friend_id) {
                $refer_code = User::getUserFieldById($friend_id, 'refer_code');
                if (empty($refer_code)) {
                    $not_exists_user_ids .= $friend_id . ',';
                    continue;
                }
                $friend_copy_ids = $friend_ids;
                unset($friend_copy_ids[$key]);

                foreach ($friend_copy_ids as $friend_copy_id) {
                    $refer_code = User::getUserFieldById($friend_id, 'refer_code');
                    if (empty($refer_code)) {
                        $not_exists_user_ids .= $friend_id . ',';
                        continue;
                    }
                    UserFriend::bindFriendByFriendUserId($friend_id, $friend_copy_id, 'admin_bind');
                    UserFriend::bindFriendByFriendUserId($friend_copy_id, $friend_id, 'admin_bind');
                }
            }
        }

        $not_exists_user_ids = rtrim($not_exists_user_ids, ',');
        $not_exists_user_ids = implode(',', array_unique(array_filter(explode(',', $not_exists_user_ids))));
        return $this->successReturn($not_exists_user_ids);


    }


}